package com.dog.modules.file.service.impl;

import cn.hutool.core.lang.Assert;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.dog.modules.file.model.SysFileUploadVO;
import com.dog.modules.file.service.OssService;
import com.dog.modules.file.utils.FileUtils;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.InputStream;

/**
 * Aliyun 对象存储服务类
 *
 * @author haoxr
 * @since 2.3.0
 */
@Component
@ConditionalOnProperty(value = "oss.type", havingValue = "aliyun")
@ConfigurationProperties(prefix = "oss.aliyun")
@RequiredArgsConstructor
@Data
public class AliyunOssService implements OssService {
    /**
     * 服务Endpoint
     */
    private String endpoint;
    /**
     * 访问凭据
     */
    private String accessKeyId;
    /**
     * 凭据密钥
     */
    private String accessKeySecret;
    /**
     * 存储桶名称
     */
    private String bucketName;

    private OSS aliyunOssClient;

    @PostConstruct
    public void init() {
        aliyunOssClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }


    @Override
    @SneakyThrows
    public SysFileUploadVO uploadFile(MultipartFile file) {
        String path = FileUtils.getPath(file.getOriginalFilename());
        //  try-with-resource 语法糖自动释放流
        try (InputStream inputStream = file.getInputStream()) {
            // 设置上传文件的元信息，例如Content-Type
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            // 创建PutObjectRequest对象，指定Bucket名称、对象名称和输入流
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, inputStream, metadata);
            // 上传文件
            aliyunOssClient.putObject(putObjectRequest);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败");
        }
        // 获取文件访问路径
        String fileUrl = "https://" + bucketName + "." + endpoint + "/" + path;
        SysFileUploadVO sysFileUploadVO = new SysFileUploadVO();
        sysFileUploadVO.setName(path);
        sysFileUploadVO.setUrl(fileUrl);
        sysFileUploadVO.setSize(file.getSize());
        sysFileUploadVO.setPlatform("aliyun");
        return sysFileUploadVO;
    }

    @Override
    public boolean deleteFile(String fileUrl) {
        Assert.notBlank(fileUrl, "删除文件路径不能为空");
        String fileHost = "https://" + bucketName + "." + endpoint; // 文件主机域名
        String fileName = fileUrl.substring(fileHost.length() + 1); // +1 是/占一个字符，截断左闭右开
        aliyunOssClient.deleteObject(bucketName, fileName);
        return true;
    }
}
